<template>
  <div>
    <MyTable :list="list">
      <template #title>
        <th>序号</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>
      <template #body="{ row, index }">
        <td>{{ row.id }}</td>
        <td>{{ row.goods_name }}</td>
        <td>{{ row.goods_price }}</td>
        <td class="my-goods-list">
          <input
            type="text"
            v-if="row.inputVisible"
            v-focus
            v-model="row.inputValue"
            @keydown.esc="row.inputValue = ''"
            @keydown.enter="addFn(row)"
            @blur="row.inputVisible = false"
          />
          <button
            v-else
            @click="row.inputVisible = true"
            style="display: block"
            class="btn btn-primary btn-sm add-tag"
          >
            +Tag
          </button>
          <span
            v-for="(item, index) in row.tags"
            :key="index"
            class="badge badge-warning"
            >{{ item }}</span
          >
        </td>
        <td>
          <button @click="btn(index)" class="btn btn-danger btn-sm">
            删除
          </button>
        </td>
      </template>
    </MyTable>
  </div>
</template>

<script>
import MyTable from "./MyTable.vue";
export default {
  data() {
    return {
      list: [],
      falg: false,
    };
  },
  components: {
    MyTable,
  },
  created() {
    this.$axios({
      url: "/api/goods",
    })
      .then((res) => {
        this.list = res.data.data;
      })
      .catch((err) => {
        console.log(err);
      });
  },
  methods: {
    btn(index) {
      this.list.splice(index, 1);
    },
    addFn(row) {
      if (row.inputValue.trim().length === 0) {
        alert("输入不能为空！");
        return;
      }
      row.tags.push(row.inputValue);
      row.inputValue = "";
    },
  },
  directives: {
    focus: {
      inserted(el) {
        el.focus();
      },
    },
  },
};
</script>

<style scoped lang="less">
.my-goods-list {
  .badge {
    margin-right: 5px;
  }
}
</style>
